home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 17631 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.8 KB  |  52 lines

  1. Newsgroups: comp.lang.c++
  2. Path: in2.uu.net!allegra!alice!ark
  3. From: ark@research.att.com (Andrew Koenig)
  4. Subject: Re: downcast with virtual base class - illegal but why
  5. Message-ID: <Dpyp25.EDq@research.att.com>
  6. Organization: AT&T Research, Murray Hill NJ
  7. References: <31741697.7881@zurich.ibm.com>
  8. Date: Tue, 16 Apr 1996 15:44:29 GMT
  9.  
  10. In article <31741697.7881@zurich.ibm.com> Keith Whittingham <wgk@zurich.ibm.com> writes:
  11.  
  12. > I know the downcast from a virtual base class is illegal but why?
  13.  
  14. Because there may be more than one derived class subobject of the
  15. same object with the same type and the same virtual base class object.
  16. In that case, there is no way to tell which of the derived class
  17. subobjects was intended.  For example:
  18.  
  19.     class V { };
  20.  
  21.     class B: public virtual V { };
  22.  
  23.     class D: public B { }
  24.  
  25.     class E: public B, public D { };
  26.  
  27. Every object of class E now contains a B part and a D part.
  28. The D part contains a(nother) B part.  Each B part refers to the
  29. same V object.  So suppose we have:
  30.  
  31.     V* vp;
  32.  
  33.     B* bp = (B*) vp;
  34.  
  35. where vp really points at the V part of an E object.  The cast is
  36. ambiguous -- there is no way to tell which B was intended.
  37.  
  38. Now, you may agree that this example should be illegal because
  39. the ambiguity is obvious.  But suppose we deleted the definitions
  40. of classes D and E.  Wouldn't that remove the ambiguity?
  41.  
  42. Unfortunately, it wouldn't.  For example, the definitions of D
  43. and E might have moved to a different translation unit entirely.
  44. Their mere existence in that translation unit renders the cast
  45. in this one ambiguous.  That means that in general there is no way
  46. to determine at compile time whether any cast from a virtual base
  47. class to a derived class is ambiguous; C++ therefore prohibits
  48. them all.
  49. -- 
  50.                 --Andrew Koenig
  51.                   ark@research.att.com
  52.